/* all js use for all web
 * author: jmdvirus
 */

/**
 * every page use it for nav
 */
$(function() {
    // TipsBrower();
    window.isie = new Is();
    $('ul.mainnav a').stop().animate({
        'marginTop': '-30px'
    }, 1000);
    $('ul.mainnav > li').hover(
        function() {
            $('a', $(this)).stop().animate({
                'marginTop': '0px'
            }, 200);
        },
        function() {
            $('a', $(this)).stop().animate({
                'marginTop': '-30px'
            }, 200);
        }
    );


    // 
    String.prototype.trim = function() {
        return this.replace(/(^\s*)|(\s*$)/g, "");
    };
    $('div.jk-input-text,div.jk-input-text-none').bind("DOMNodeInserted", function() {
        if (window.isie.ie) {
            $("div.jk-input-text p").replaceWith("<br>");
            $("div.jk-input-text-none p").replaceWith("<br>");
        } else {
            // $("div.jk-input-text div").replaceWith('<br>');
            // $("div.jk-input-text-none div").replaceWith("<br>");
        }
    });

    bindDivTips('div.jk-input-text');

    setDivEditable($('div.jk-input-text'));

    /*
     * there are two time display
     * first hide 2
     * when mouse move display 2
     * and display 1 when mouse leave
     */
    $("div.time1,span.time1").mouseenter(function() {
        var display = $(this).siblings('div.time2,span.time2');
        $(this).css('display', 'none');
        display.css("display", "block");
    });
    $("div.time2,span.time2").mouseleave(function() {
        var display = $(this).siblings('div.time1,span.time1');
        display.css('display', 'block');
        $(this).css("display", "none");
    });
});

function bindDivTips(id) {
    var pos = id;
    if (id !== "") pos = "div.jk-input-text";
    $(pos).click(function() {
        var tips = $(this).children('span.tips');
        if (tips != undefined) tips.remove();
    });
}

/**
 * open and close modal dialog use bootstrap
 * @param string
 */
function openAddItem(string) {
    var additem = $(string);
    additem.modal();
}

function closeAddItem(string) {
    var additem = $(string);
    additem.modal('hide');
}

/**
 * ajax send post
 * @param url
 * @param alldata
 * @param fn
 * @returns {Boolean}
 */
function jk_send_request_post(url, alldata, fn) {
    var run_url = url;

    $.ajax({
        type: "post",
        typeData: "json",
        url: run_url,
        data: alldata,
        complete: fn
    });

    return true;
}

function jk_send_request_get(url, alldata, fn) {
    var run_url = url;

    $.ajax({
        type: "get",
        typeData: "json",
        url: run_url,
        data: alldata,
        complete: fn
    });

    return true;
}

function jk_open_tips(id) {
    $(id).wrap('<div id="jk_overlay" />');
    $(id).fadeIn('normal');
}

function jk_close_tips(id) {
    $(id).unwrap();
    $(id).css("display", "none");
}

function jk_create_overlay(id) {
    $(id).after("<div id='jk_overlay'></div>");
}

function jk_destroy_overlay() {
    $('#jk_overlay').remove();
}


/**
 * enable /disable input
 * @param {Object} name which to option name=xxx
 * @param {Object} enable 0 -- disable 1 -- enable
 */
function enableInput(name, enable) {
    var sect = 'input[name=' + name + ']';
    if (enable == 1) {
        $(sect).attr('disabled', false);
    } else $(sect).attr('disabled', true);
}

/**
 * result success or send fail
 * @param {Object} data
 * @param {Object} textStatus
 */
function dealSuccess(data, textStatus) {
    if (textStatus != "success") {
        alert("对不起，上传过程失败，可能是临时网络原因");
        return false;
    }
    var result = $.parseJSON(data.responseText);

    switch (result.status) {
        case 0: // means success
            alert("成功操作 ^.^");
            window.location.reload();
            return true;
        case -103:
            alert("数据库不给面子，查询失败 -.-");
            return false;
        case -107: // item is exist
            alert("速度太慢了，已经被别人添加了 -.-");
            return false;
        case -106: // item is not exist
            alert("你确定你找的东西是存在的？ -.-");
            return false;
        case -104: // write db error
            alert("Oh! 数据库太不给面子，不让写入 -.-");
            return false;
        case -110: // save content is null
            alert("什么都不写，你怎么知道哪个是你的呢？ -.-");
            return false;
        case -109: // code wrong
            alert("guy! 你哪来的？确定你有权限操作？ -.-");
            return false;
        case -111:
            alert("你的创建时间怎么可能是未来的？难道你是穿越来的？");
            return false;
        default:
            return result;
    }
}

/* check what browser */
function Is() {
    var agent = navigator.userAgent.toLowerCase();
    this.major = parseInt(navigator.appVersion); //主版本号
    this.minor = parseFloat(navigator.appVersion); //全版本号
    this.ns = ((agent.indexOf('mozilla') != -1) &&
        ((agent.indexOf('spoofer') == -1) && //是否 Netscape
            (agent.indexOf('compatible') == -1)));
    this.ns2 = (this.ns && (this.major == 3)); //是否 Netscape 2
    this.ns3 = (this.ns && (this.major == 3)); //是否 Netscape 3
    this.ns4b = (this.ns && (this.minor < 4.04)); //是否 Netscape 4 低版本
    this.ns4 = (this.ns && (this.major >= 4)); //是否 Netscape 4 高版本
    this.ie = (agent.indexOf("msie") != -1); //是否 IE
    this.ie3 = (this.ie && (this.major == 2)); //是否 IE 3
    this.ie4 = (this.ie && (this.major >= 4)); //是否 IE 4
    this.ie5 = (this.ie && (this.major >= 5)); // IE 5
    this.op3 = (agent.indexOf("opera") != -1); //是否 Opera 3
    this.win = (agent.indexOf("win") != -1); //是否 Windows 版本
    this.mac = (agent.indexOf("mac") != -1); //是否 Macintosh 版本
    this.unix = (agent.indexOf("x11") != -1); //是否 Unix 版本
}

function TipsBrower() {
    var is = new Is();
    if (is.ie) {
        $('body').append("您正在使用ie或ie类浏览器，本网站尚不能完美支持这类浏览器，若有需要，可更新使用其它浏览器，推荐chrome");
    }
}

function setDivEditable(id) {
    if (window.isie.ie) {
        id.attr('contenteditable', 'true').css("background-color", "white");
    } else {
        id.attr('contenteditable', 'plaintext-only').css("background-color", "white");
    }
}

function setDivUneditable(id) {
    id.removeAttr('contenteditable').css("background-color", "rgba(232,232,232,0.9)");
}

/*
 * get cursor pos
 */
function getMousePoint(ev) {
    // 定义鼠标在视窗中的位置
    var point = {
        x: 0,
        y: 0,
        w: 0,
        h: 0
    };

    // 如果浏览器支持 pageYOffset, 通过 pageXOffset 和 pageYOffset 获取页面和视窗之间的距离
    if (typeof window.pageYOffset != 'undefined') {
        point.x = window.pageXOffset;
        point.y = window.pageYOffset;
    }
    // 如果浏览器支持 compatMode, 并且指定了 DOCTYPE, 通过 documentElement 获取滚动距离作为页面和视窗间的距离
    // IE 中, 当页面指定 DOCTYPE, compatMode 的值是 CSS1Compat, 否则 compatMode 的值是 BackCompat
    else if (typeof document.compatMode != 'undefined' && document.compatMode != 'BackCompat') {
        point.x = document.documentElement.scrollLeft;
        point.y = document.documentElement.scrollTop;
    }
    // 如果浏览器支持 document.body, 可以通过 document.body 来获取滚动高度
    else if (typeof document.body != 'undefined') {
        point.x = document.body.scrollLeft;
        point.y = document.body.scrollTop;
    }

    // 加上鼠标在视窗中的位置
    point.x += ev.clientX;
    point.y += ev.clientY;

    point.w = document.body.scrollWidth;
    point.h = document.body.scrollHeight;

    // 返回鼠标在视窗中的位置
    return point;
}

function relativePoint(ev, width, height) {
    var point = getMousePoint(ev);
    // alert(point.x + ";" + point.y + "--" + point.w + ";" + point.h);
    if (point.x + width > point.w) {
        point.x = point.w - width;
    }
    if (point.y + height > point.h) {
        point.y = point.h - height;
    }
    // alert(point.x + ";" + point.y);
    return point;
}

function confirmWindow(event, delTips) {
    $confirm = $('#jk_confirm');
    $confirm.remove();
    var confirm_obj = "<div id='jk_confirm'>" +
        delTips.content +
        "<button class='btn btn-danger sure'>sure</button><button class='btn cancel'>cancel</button>" +
        "</div>";
    var point = relativePoint(event, delTips.width + 40, delTips.height + 20);
    $('body').after(confirm_obj);
    $("#jk_confirm").css({
        'top': point.y,
        'left': point.x
    });
    jk_create_overlay('#jk_confirm');

    $("#jk_confirm button").click(function() {
        var clicked = $(this).text();
        if (clicked == "sure") {
            var string = findInputToString("#jk_confirm");
            var sendString = delTips.string;
            if (string != "") sendString += string;
            delTips.callback(sendString);
        } else if (clicked == "cancel") {
            confirmWindowDestroy("#jk_confirm");
            return false;
        }
    });
    return false;
}

function confirmWindowDestroy(id) {
    jk_destroy_overlay();
    $(id).remove();
}

/*
 * find all input from id
 * and contain to a string return
 */
function findInputToString(id) {
    var allInput = $(id + " input");
    var inputString = new Array(10);
    for (var i = 0; i < allInput.length; i++) {
        if (allInput[i].type == "text") {
            inputString[i] = allInput[i].name + "=" + allInput[i].value.trim();
        }
    }

    var sendString = "";
    for (var i = 0; i < inputString.length; i++) {
        if (inputString[i] === undefined) break;
        sendString += "&" + inputString[i];
    }
    return sendString;
}

function JKTips(incontent, width, height, doDel) {
    var width = 200,
        height = 200,
        content = "";
    var callback = null;
    var string = "";
    _this = this;
    var init = function() {
        _this.width = width;
        _this.height = height;
        _this.content = incontent;
        _this.callback = doDel;
    };

    init();
}

function create_show_window(winName) {
    $winName = $("#" + winName);
    $winName.remove();

    var obj = "<div class='jk-layout-show' id='" + winName + "' >test" +
        "</div>";
    $('body').append(obj);

    $("#" + winName).css({
        "background-color": "red"
    });
    set_windows_size(winName);
}

function change_window_size(winName) {
    $winName = $("#" + winName);
    if ($winName == undefined) return false;
    alert("test");
    set_windows_size(winName);
}

function set_windows_size(winName) {
    var height = $(window).height();
    var width = $(window).width();

    var top = 80,
        left = 80;

    var w_h = height - 2 * top;
    var w_w = width - 2 * left;

    $("#" + winName).css({
        "top": top,
        "left": left,
        "width": w_w,
        "height": w_h
    });
}

/**
 * Here implement falldown pics from top
 * The pics format is img/hk(n).png
 */
function jk_falldown(img_counts) {
    var exist_time = 10000; // remove the pics when the time over
    var max_width = $(window).width();
    var max_height = $(window).height();

    // the pics start position
    var pos_start = parseInt(Math.floor(max_width * Math.random()));
    // the pics end position
    var pos_end = parseInt(Math.floor(max_width * Math.random()));
    // the time generate which pic
    var img_index = parseInt(Math.floor(img_counts * Math.random())) + 1;

    // define one object of img to display
    var img = $("<img src='imgs/hk-" + img_index + ".png' style='width:40px;height:40px;position:absolute;top:0px;left:" + pos_start + "px;'/>");
    $("body").append(img);

    // falldown slowly
    img.animate({
            top: max_height,
            left: pos_end
        },
        exist_time);

    setTimeout(function() {
        /* stuff to do after animation is complete */
        img.remove();
    }, exist_time);
}